package com.weixing.mall.provider.controller.front;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.GenderEnum;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.api.model.vo.AgentVo;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.model.domain.Member;
import com.weixing.mall.provider.model.dto.ChgMobileDto;
import com.weixing.mall.provider.model.dto.MemberDto;
import com.weixing.mall.provider.model.dto.MemberLocDto;
import com.weixing.mall.provider.model.vo.MemberAgentVo;
import com.weixing.mall.provider.model.vo.MemberIndexVo;
import com.weixing.mall.provider.model.vo.MemberVo;
import com.weixing.mall.provider.service.IMemberService;
import com.weixing.mall.push.CidAlias;
import com.weixing.mall.push.GtComponent;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 个人资料Api
 *
 * @author  wx
 * @date  2019/9/16 17:08
 * @since  1.0
 */
@RestController
@RequestMapping("/front/member")
public class FrontMemberController extends BaseController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private AgentServiceRpc agentServiceRpc;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GtComponent gtComponent;


    /**
     * 查询详情
     *
     * @return 详情
     */
    @PostMapping("detail")
    public Result<MemberVo> selectDetail() {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long memberId = memAuth.getMid();
        return ResultUtil.success(memberService.selectDetail(memberId));
    }


    /**
     * 修改头像
     *
     * @param memberDto   参数
     * @return 结果
     */
    @PostMapping("setAvator")
    public Result updateAvator( @RequestBody MemberDto memberDto) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        memberService.updateAvator(memberDto.getAvator(), memAuth.getMid());
        return ResultUtil.success();
    }


    /**
     * 修改昵称
     *
     * @param memberDto 参数
     * @return 结果
     */
    @PostMapping("setNickName")
    public Result setNickName(@RequestBody MemberDto memberDto) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Member member = memberService.getById(memAuth.getMid());
        member.setNickName(memberDto.getNickName());
        memberService.updateById(member);
        return ResultUtil.success();
    }

    /**
     * 修改出生日期
     *
     * @param memberDto  参数
     * @return 结果
     */
    @PostMapping("setBirth")
    public Result updateBirthDay( @RequestBody MemberDto memberDto) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        memberService.updateBirthDay(memberDto.getBirthDay(), memAuth.getMid());
        return ResultUtil.success();
    }

    /**
     * 修改性别
     *
     * @param gender  性别
     * @return  结果
     */
    @PostMapping("setGender/{gender}")
    public Result updateGender( @PathVariable GenderEnum gender) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        memberService.updateGender(gender.getValue(), memAuth.getMid());
        return ResultUtil.success();
    }

    /**
     * 修改手机号
     * @param chgMobile 参数
     * @return 结果
     */
    @PostMapping("setMobile")
    public Result updateMobile(@Validated @RequestBody ChgMobileDto chgMobile) {
        MemAuth auth = AuthUtil.getMemberExt();
        String mobile = chgMobile.getMobile();
        String smsCode = chgMobile.getSmsCode();
        boolean mobileExist = memberService.checkMobileExist(mobile);
        if (mobileExist) {
            return ResultUtil.error("手机号已被占用");
        }
        // 校验短信验证码
        String key = GlobalConstant.REDIS_PRE_SMS + mobile;
        String verifyCode = stringRedisTemplate.opsForValue().get(key);
        if (StringUtil.isBlank(verifyCode)) {
            // 短信验证码已过期
            return ResultUtil.error(ResultCodeEnum.CODE_10011007);
        } else if (!smsCode.equals(verifyCode)) {
            // 短信验证码验证失败
            return ResultUtil.error(ResultCodeEnum.CODE_10011005);
        }
        memberService.updateMobile(mobile, auth.getMid());

        Member member = memberService.getById(auth.getMid());
        if (WhetherEnum.YES.getValue().equals(member.getIsAgent())) {
            // 如果是代理商，还需要同步修改代理商的手机号
            agentServiceRpc.updateMobile(member.getAgentRoleBindId(), mobile);
        }
        return ResultUtil.success();
    }

    /**
     * 修改地区
     *
     * @param memberLocDto  参数
     * @return 结果
     */
    @PostMapping("setLoc")
    public Result updateProvincesPath(@RequestBody MemberLocDto memberLocDto) {
        MemAuth auth = AuthUtil.getMemberExt();
        memberService.updateProvincesPath(memberLocDto, auth.getMid());
        return ResultUtil.success();
    }

    /**
     * 会员主页
     *
     * @return  主页数据
     */
    @GetMapping("index")
    public Result<MemberIndexVo> selectByMemberIdList() {
        MemAuth memAuth = AuthUtil.getMemberExt();
        return ResultUtil.success(memberService.selectMemberIndex(memAuth.getMid()));
    }

    /**
     * 重新綁定代理商/手机号或者代理商编号
     *
     * @param searchParam  手机号/代理商编号
     * @return 结果
     */
    @GetMapping("reBindAgent")
    public Result reBindAgent(String searchParam) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Member member = memberService.getById(memAuth.getMid());
        Result<AgentVo> agentVoResult = agentServiceRpc.selectByMobileOrSn(searchParam);
        if (!agentVoResult.isSuccess()) {
            return ResultUtil.error("代理商服务不可用");
        }
        AgentVo agentVo = agentVoResult.getData();
        if (null == agentVo) {
            return ResultUtil.error("代理商不存在");
        }
        if (IsEnableEnum.DISABLE == agentVo.getIsEnable()) {
            return ResultUtil.error("该代理已被禁用，不能够绑定");
        }
        if (WhetherEnum.NO == agentVo.getIsBind()) {
            return ResultUtil.error("该代理尚未绑定结构树，不能够绑定");
        }
        Date now = new Date();
        if (DateUtil.compare(now, agentVo.getMaturityTime()) > 0) {
            return ResultUtil.error("该代理已过期，不能够绑定");
        }

        if (WhetherEnum.YES.getValue().equals(memAuth.getAf())) {
            return ResultUtil.error("您是代理，不能够再绑定其他代理");
        }

        member.setAgentId(agentVo.getId());
        member.setAgentSn(agentVo.getAgentSn());
        member.setAgentBindTime(new Date());
        member.setAgentName(agentVo.getAgentName());
        member.setKefuId(agentVo.getCustomerId());
        member.setKefuName(agentVo.getCustomerName());
        member.setKefuBindTime(new Date());
        memberService.updateById(member);
        return ResultUtil.success();
    }

    /**
     * 我綁定的代理商
     *
     * @return  代理商
     */
    @GetMapping("myAgent")
    public Result<MemberAgentVo> myAgent() {
        MemAuth memAuth = AuthUtil.getMemberExt();
        MemberAgentVo vo = null;
        Member member = memberService.getById(memAuth.getMid());
        Long agentId = member.getAgentId();
        if (null == agentId) {
            return ResultUtil.error("您还没有绑定代理商");
        }
        Result<AgentRpcVo> voResult = agentServiceRpc.selectByAgentId(agentId);
        AgentRpcVo data = voResult.getData();
        vo = new MemberAgentVo();
        vo.setAgentName(data.getAgentName());
        vo.setAgentSn(data.getAgentSn());
        vo.setAgentMobile(data.getMobile());
        vo.setAgentBindTime(DateUtil.format(member.getAgentBindTime(), DatePattern.NORM_DATETIME_PATTERN));
        return ResultUtil.success(vo);
    }


    /**
     * 解除綁定代理商
     *
     * @return 结果
     */
    @GetMapping("unBind")
    public Result unBindAgent() {
        MemAuth memAuth = AuthUtil.getMemberExt();
        memberService.unBindAgent(memAuth.getMid());
        return ResultUtil.success();
    }

    /**
     * 校验是否已申请代理
     *
     * @return 结果
     */
    @GetMapping("checkAgentApply")
    public Result checkAgentApply() {
        MemAuth auth = AuthUtil.getMemberExt();
        Member member = memberService.getById(auth.getMid());
        Result<AgentVo> byMobile = agentServiceRpc.findByMobile(member.getMobile());
        if (!byMobile.isSuccess()) {
            return ResultUtil.error("校验是否已申请代理请求失败，请稍后重试");
        } else {
            if (null != byMobile.getData()) {
                return ResultUtil.success(WhetherEnum.YES.getValue());
            }
        }
        return ResultUtil.success(WhetherEnum.NO.getValue());
    }


    /**
     * 绑定个推cid
     *
     * @param cid   cid
     * @return  结果
     */
    @PostMapping("bindCid/{cid}")
    public Result bindCid( @PathVariable String cid) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long mid = memAuth.getMid();
        Member byId = memberService.getById(mid);
        memberService.updateCid(byId.getMobile(), mid);
        List<CidAlias> list = Lists.newArrayList();
        CidAlias alias = new CidAlias();
        alias.setCid(cid);
        alias.setAlias(byId.getMobile());
        list.add(alias);
        gtComponent.bindAlias(list);
        return ResultUtil.success();
    }

}
